﻿using AutoMapper;
using PagedList;
using SIG.Infrastructure.Configs;
using SIG.Infrastructure.Helper;
using SIG.InputModel.Admin.Videos;

using SIG.Service;
using SIG.ViewModel;
using SIG.ViewModel.Admin.Videos;
using SIG.WebMVC.Filters;
using System;
using System.Collections.Generic;
using System.Web.Mvc;
using System.Xml.Linq;
using System.Linq;
using SIG.Resources.Admin;
using SIG.DAL.Dapper.Repositories;
using SIG.DAL.Dapper.Model;

namespace SIG.WebMVC.Areas.Admin.Controllers
{
    [SIGAuth]
    public class VideoController : BaseController
    {

        private readonly VideoRepository _videoRepository;
        //private readonly PageMetaRepository _pageMetaRepository;
        private readonly PageMetaRepository _pageMetaRepository;
        private readonly IMapper _mapper;

        public VideoController(IMapper mapper)
        {
            _videoRepository = new VideoRepository();
            _pageMetaRepository = new PageMetaRepository();
            _mapper = mapper;

        }
        // GET: Admin/Video

        #region Video

        public ActionResult Index(int? page, string keyword)
        {
            VideoListVM videoListVM = GetElements(page, keyword);
         
            ViewBag.PageSizes = new SelectList(Site.PageSizes());
            return View(videoListVM);

        }

        private VideoListVM GetElements(int? page, string keyword)
        {
            var videoListVM = new VideoListVM()
            {
                Keyword = keyword,
                PageIndex = (page ?? 1),
                PageSize = SettingsManager.Video.PageSize
            };
            int totalCount;
            var videolist = _videoRepository.GetListPagedItems(videoListVM.PageIndex, videoListVM.PageSize, videoListVM.Keyword, out totalCount);
           
            videoListVM.TotalCount = totalCount;
            videoListVM.Videos = new StaticPagedList<Video>(videolist, videoListVM.PageIndex, videoListVM.PageSize, videoListVM.TotalCount); ;
            return videoListVM;
        }


        [HttpPost]
        public JsonResult PageSizeSet(int pageSize)
        {
            try
            {
                var xmlFile = Server.MapPath("~/Config/VideoSettings.config");
                XDocument doc = XDocument.Load(xmlFile);

                var item = doc.Descendants("Settings").FirstOrDefault();
                item.Element("PageSize").SetValue(pageSize);
                doc.Save(xmlFile);

                return Json(AR, JsonRequestBehavior.DenyGet);
            }
            catch (Exception ex)
            {
                AR.Setfailure(ex.Message);
                return Json(AR, JsonRequestBehavior.DenyGet);
            }
        }


        [HttpGet]
        public ActionResult Add()
        {
            var vCategory = new VideoIM()
            {
                Active = true
            };
            //vCategory.PageIndex = pageIndex;
            //vCategory.PageSize = pageSize;
            //vCategory.Keyword = keyword;


            return PartialView("_Add", vCategory);
        }



        [HttpPost]
        public JsonResult Add(VideoIM vm)
        {

            if (!ModelState.IsValid)
            {
                AR.Setfailure(GetModelErrorMessage());
                return Json(AR, JsonRequestBehavior.DenyGet);
            }

            var video = _mapper.Map<VideoIM, Video>(vm);
            video.ViewCount = 0;
            video.CreatedBy = Site.CurrentUserName;
            video.CreatedDate = DateTime.Now;

            var result = _videoRepository.Create(video);

            if (result > 0)
            {
                var pageMeta = new PageMeta()
                {
                    ObjectId = result.ToString(),
                    Title = string.IsNullOrEmpty(vm.SEOTitle) ? vm.Title : vm.SEOTitle,
                    Keyword = string.IsNullOrEmpty(vm.Keywords) ? vm.Title : vm.Keywords.Replace('，', ','),
                    Description = vm.Description,
                    ModelType = (short)ModelType.VIDEO
                };
                _pageMetaRepository.Create(pageMeta);
            }
          
            

            int count;
            int pageSize = SettingsManager.Video.PageSize;
            var list = _videoRepository.GetListPagedItems(1, pageSize, string.Empty,out count);
       
            AR.Data = RenderPartialViewToString("_VideoList", list);

            AR.SetSuccess(String.Format(Messages.AlertCreateSuccess, EntityNames.Video));
            return Json(AR, JsonRequestBehavior.DenyGet);

        }


        [HttpGet]
        public ActionResult Edit(int id)
        {

            Video video = _videoRepository.GetById(id);
            if (video == null)
            {
                AR.Setfailure(Messages.HttpNotFound);
                return Json(AR, JsonRequestBehavior.AllowGet);
            }

            var vm = _mapper.Map<VideoIM>(video);

            var pageMeta = _pageMetaRepository.GetPageMeta(ModelType.VIDEO, vm.Id.ToString());
            if (pageMeta != null)
            {
                vm.SEOTitle = pageMeta.Title;
                vm.Keywords = pageMeta.Keyword;
                vm.Description = pageMeta.Description;
            }

            return PartialView("_Edit", vm);
        }

        [HttpPost]
        [ValidateAntiForgeryToken]

        public JsonResult Edit(VideoIM vm)
        {

            if (!ModelState.IsValid)
            {
                AR.Setfailure(GetModelErrorMessage());
                return Json(AR, JsonRequestBehavior.DenyGet);
            }

            var video = _videoRepository.GetById(vm.Id);
            video.Active = vm.Active;
            video.VideoUrl = vm.VideoUrl;
            video.OgvUrl = vm.OgvUrl;
            video.WebmUrl = vm.WebmUrl;
            video.Title = vm.Title;
            video.Thumbnail = vm.Thumbnail;
            video.Preview = vm.Preview;
            video.UpdatedBy = Site.CurrentUserName;
            video.UpdatedDate = DateTime.Now;

            //video = _mapper.Map<VideoIM, Video>(vm);
            _videoRepository.Update(video);


            var pageMeta = _pageMetaRepository.GetPageMeta(ModelType.VIDEO, vm.Id.ToString());
            pageMeta = pageMeta ?? new PageMeta();          

            pageMeta.ObjectId = vm.Id.ToString();
            pageMeta.Title = string.IsNullOrEmpty(vm.SEOTitle) ? vm.Title : vm.SEOTitle;
            pageMeta.Keyword = string.IsNullOrEmpty(vm.Keywords) ? vm.Title : vm.Keywords.Replace('，', ',');
            pageMeta.Description = vm.Description;
            pageMeta.ModelType = (short)ModelType.VIDEO;

            if (pageMeta.Id > 0)
            {
                _pageMetaRepository.Update(pageMeta);
            }
            else
            {
                _pageMetaRepository.Create(pageMeta);
            }
          

          //  var videoVM = _mapper.Map<VideoVM>(video);

            AR.Id = video.Id;
            AR.Data = RenderPartialViewToString("_VideoItem", video);

            AR.SetSuccess(String.Format(Messages.AlertUpdateSuccess, EntityNames.Video));
            return Json(AR, JsonRequestBehavior.DenyGet);

        }

        // DELETE: /User/DeleteSite
        [HttpPost]
        [ValidateAntiForgeryToken]
        public JsonResult Delete(int id)
        {
           // Video vCategory = _videoRepository.GetById(id);                    

            _videoRepository.Delete(id);
            AR.SetSuccess(String.Format(Messages.AlertDeleteSuccess, EntityNames.Video));
            return Json(AR, JsonRequestBehavior.DenyGet);

        }


        [HttpPost]
        [ValidateAntiForgeryToken]
        public JsonResult IsActive(int id)
        {

            var vm = _videoRepository.GetById(id);
            if (vm == null)
            {
                AR.Setfailure(Messages.HttpNotFound);
                return Json(AR, JsonRequestBehavior.DenyGet);
            }

            try
            {
                vm.Active = !vm.Active;
                _videoRepository.Update(vm);
              //  var vm = _mapper.Map<VideoVM>(vCategory);

                AR.Data = RenderPartialViewToString("_VideoItem", vm);
                AR.SetSuccess(String.Format(Messages.AlertUpdateSuccess, EntityNames.Video));
                return Json(AR, JsonRequestBehavior.DenyGet);
            }
            catch (Exception ex)
            {
                AR.Setfailure(ex.Message);
                return Json(AR, JsonRequestBehavior.DenyGet);
            }
        }

        


        //[AllowAnonymous]
        //public JsonResult IsSeoNameUnique(string seoName, int? Id)
        //{
        //    return !IsExist(seoName, Id)
        //        ? Json(true, JsonRequestBehavior.AllowGet)
        //        : Json(false, JsonRequestBehavior.AllowGet);
        //}
        //[AllowAnonymous]
        //public bool IsExist(string seoName, int? id)
        //{
        //    var wType = _videoService.GetAll().Where(w => w.SeoName == seoName);
        //    if (id > 0)
        //    {
        //        wType = wType.Where(w => w.Id != id);
        //    }

        //    if (wType.Count() > 0)
        //        return true;

        //    return false;
        //}



        #endregion
    }
}